package com.orangelife.webservice.service.propFeePollfee.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.activation.DataHandler;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

import jxl.CellView;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import net.sf.json.JSONArray;

import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.orangelife.exception.AppBizException;
import com.orangelife.service.propFeeComm.IPropFeeCommService;
import com.orangelife.service.propFeeComm.model.PropFeeCommDto;
import com.orangelife.service.propFeeCommInfo.IPropFeeCommInfoService;
import com.orangelife.service.propFeePollfee.IImportPollFeeService;
import com.orangelife.service.propFeePollfee.IPropFeePollfeeService;
import com.orangelife.service.propFeePollfee.model.PollfeeEditDto;
import com.orangelife.service.propFeePollfee.model.PropFeePollfeeDto;
import com.orangelife.service.propFeePollfeeImportLog.IPropFeePollfeeImportLogService;
import com.orangelife.setting.constant.CodeConst;
import com.orangelife.setting.constant.InfoConst;
import com.orangelife.utils.PropertyUtils;
import com.orangelife.utils.StringUtils;
import com.orangelife.webservice.base.BaseService;
import com.orangelife.webservice.base.PageUtils;
import com.orangelife.webservice.service.propFeePollfee.IPropFeePollfeeWebService;

/*****************************************************************
 * Copyright(C) ORANGELIFE Corporation 2015. All Rights Reserved.
 *****************************************************************/
/*
 * ============================================================== 功能名
 * propFeePollfee类 的WebService基本作业
 * 
 * @author zhr
 * 
 * @version 1.1.0
 * 
 * @date 2016-07-25 10:47:47
 * ==============================================================
 */
@Service("webservice_propFeePollfee")
public class PropFeePollfeeWebServiceImpl extends BaseService implements
		IPropFeePollfeeWebService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Resource(name = "propFeePollfeeService")
	private IPropFeePollfeeService propFeePollfeeService;
	@Resource(name = "importPollFeeService")
	private IImportPollFeeService importPollFeeService;
	@Resource(name = "propFeeCommService")
	private IPropFeeCommService propFeeCommService;
	@Resource(name = "propFeeCommInfoService")
	private IPropFeeCommInfoService propFeeCommInfoService;
	@Resource(name = "propFeePollfeeImportLogService")
	private IPropFeePollfeeImportLogService propFeePollfeeImportLogService;

	@Override
	public Response addPropFeePollfee(HttpServletRequest servletRequest,
			PropFeePollfeeDto propFeePollfee) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		propFeePollfee.setCreateuserID(pageUtils.getBaseSession().getUserID());
		int result = propFeePollfeeService.addPropFeePollfee(propFeePollfee);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "添加实体成功");

		return this.normalResp();
	}

	@Override
	public Response editPropFeePollfee(HttpServletRequest servletRequest,
			PropFeePollfeeDto propFeePollfee) throws Exception {
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this.validateUUId(propFeePollfee.getPollfeeID(),
				"pollfeeID");
		if (error != null) {
			return error;
		}

		/************************************************
		 * 输入参数检查
		 ************************************************/
		// TODO;

		propFeePollfee.setEdituserID(pageUtils.getBaseSession().getUserID());
		int result = propFeePollfeeService.editPropFeePollfee(propFeePollfee);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "修改实体成功");

		return this.normalResp();
	}

	@Override
	public Response deletePropFeePollfee(HttpServletRequest servletRequest,
			String pollfeeID) throws Exception {
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this.validateUUId(pollfeeID, "pollfeeID");
		if (error != null) {
			return error;
		}
		int result = propFeePollfeeService
				.deletePropFeePollfeeByLogic(pollfeeID);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "删除实体成功");

		return this.normalResp();
	}

	@Override
	public Response findPropFeePollfeeByID(HttpServletRequest servletRequest,
			String pollfeeID) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this.validateUUId(pollfeeID, "pollfeeID");
		if (error != null) {
			return error;
		}
		PropFeePollfeeDto propFeePollfee = propFeePollfeeService
				.findPropFeePollfeeByID(pollfeeID);

		Map<String, Object> maps = new HashMap<String, Object>();

		if (propFeePollfee != null) {

		}

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "查询实体成功");
		return this.normalResp(propFeePollfee);
	}

	@Override
	public Response getAllPropFeePollfee(HttpServletRequest servletRequest,
			String commID, String ruleID, String search, String tsCreate,
			String pageIndex, String pageSize) throws Exception {

		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/
		List<Map<String, Object>> list = propFeePollfeeService
				.findPropFeePollfeeByPage(commID, ruleID,
						tsCreate == null ? null : tsCreate,
						search == null ? null : search, pageUtils
								.getiPageIndex(), pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response bauthFindPropFeePollfee(HttpServletRequest servletRequest,
			List<String> propFeePollfee) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeePollfee == null || propFeePollfee.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			map.put("pageEntity", propFeePollfeeService
					.bauthfindPropFeePollfee(propFeePollfee));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response bauthFindPropFeePollfees(HttpServletRequest servletRequest,
			Map<String, Object> propFeePollfee) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeePollfee == null || propFeePollfee.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			map.put("pageEntity", PropertyUtils
					.turnToEntity(propFeePollfeeService
							.bauthfindPropFeePollfeeByMap(propFeePollfee)));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response clearCache(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		propFeePollfeeService.clearCache();
		return this.normalResp();
	}

	@Override
	public Response addPropFeePollfees(HttpServletRequest servletRequest,
			List<Map<String, Object>> propFeePollfee) throws Exception {
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeePollfee == null || propFeePollfee.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			List<PropFeePollfeeDto> recordDtos = new ArrayList<PropFeePollfeeDto>();
			for (Map<String, Object> record : propFeePollfee) {
				if (!record.containsKey("pollfeeID")) {
					throw new AppBizException(2, "亲，公摊录入信息");

				}
				if (!record.containsKey("ruleID")) {
					throw new AppBizException(2, "亲，规则信息");
				}
				if (!record.containsKey("curAmount")) {
					throw new AppBizException(2, "亲,公摊录入信息");
				}

				if (record.get("pollfeeID") == null) {
					throw new AppBizException(2, "亲，表信息");

				}

				if (record.get("ruleID") == null) {
					throw new AppBizException(2, "亲，规则信息");
				}
				if (record.get("curAmount") == null) {
					throw new AppBizException(2, "亲,本期信息");

				}
				record.put("userID", pageUtils.getBaseSession().getUserID());
			}

			propFeePollfeeService.addPropFeePollfee(propFeePollfee);
			map.put("errInfo", "ok");
			map.put("errCode", "0");
			logger.info(pageUtils.getBaseSession().getLoginName() + "在"
					+ pageUtils.getBaseSession().getLoginType() + "端"
					+ new Date() + "时" + "添加"
					+ JSONArray.fromObject(recordDtos) + "成功");
		} catch (AppBizException e) {
			return this.abnormalResp(e.getCode(), e.getMessage());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response ImportRecord(HttpServletRequest servletRequest,
			HttpServletResponse servletResponse, String commID,
			List<Attachment> attachments) throws Exception {
		String fileName = "";
		if (attachments == null || attachments.size() == 0) {
			throw new AppBizException(100002, "请选择要上传的文件");
		}
		Sheet sheet = null;
		for (Attachment attachment : attachments) {

			DataHandler item = attachment.getDataHandler();
			fileName = item.getName();
			InputStream inputStream = item.getInputStream();
			fileName = new String(fileName.getBytes("iso-8859-1"), "utf-8");

			org.apache.poi.ss.usermodel.Workbook book = null;

			if (fileName.endsWith(".xls")) {
				book = new HSSFWorkbook(inputStream);
			} else if (fileName.endsWith(".xlsx")) {
				book = new XSSFWorkbook(inputStream);
			} else {
				throw new AppBizException(100002, "文件格式错误");
			}
			sheet = book.getSheetAt(0);// 第一个工作表
			try {
				importPollFeeService.importPollFee(sheet, commID, fileName);
			} catch (AppBizException e) {
				return this.normalResp(e.getCode(), e.getMessage());
			}

		}

		return this.normalResp();

	}

	@Override
	public Response downPollfee(HttpServletRequest servletRequest,
			final HttpServletResponse servletResponse, String search,
			String commID, String ruleID, final String comm) throws Exception {

		if (StringUtils.isBlank(commID)) {
			throw new AppBizException(2, "亲小区信息");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("commID", commID);
		map.put("ruleID", ruleID);
		final List<Map<String, Object>> list = propFeePollfeeService
				.findPropFeePollfee(commID, ruleID, null, search);

		final Map<String, String> nextTime = propFeeCommInfoService
				.findLastDate(commID);

		if (nextTime == null || nextTime.size() < 0) {
			throw new AppBizException(2, "亲小区期数");
		}

		/************************************************
		 * 返回结果设定
		 ************************************************/
		String info = "规则ID,房屋ID,类目名称,规则名称,房屋类型,楼栋,单元,房号,期数, 本期金额";

		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		final String filename = df.format(new Date());
		StreamingOutput stream = null;
		final String propFeeMeterType[] = { "", "车位", "住宅", "商铺", "商场","写字楼" };
		final PropFeeCommDto propFeeComm = propFeeCommService
				.findPropFeeCommByID(commID);
		final String infos[] = info.split(",");
		stream = new StreamingOutput() {
			public void write(OutputStream output) throws IOException,
					WebApplicationException {
				try {
					servletResponse.setContentType("application/vnd.ms-excel");
					servletResponse.setHeader(
							"Content-Disposition",
							"attachment; filename="
									+ new String((propFeeComm.getComm()
											+ "表公摊费用录入" + filename + ".xls")
											.getBytes("UTF-8"), "iso8859-1"));
					servletResponse.setHeader("Pragma", "No-cache");
					servletResponse.setHeader("Cache-Control", "No-cache");
					servletResponse.setDateHeader("Expires", 0); // 这个地方一定要进行编码的转换要不然中文字符会出现乱码.
					// 设置下载头信息.end,
					// SimpleDateFormat df = new
					// SimpleDateFormat("yyyy-MM-dd");

					InputStream fis = null;
					// PrintWriter out = response.getWriter();
					try {
						output = servletResponse.getOutputStream();
						jxl.write.WritableWorkbook wwb = Workbook
								.createWorkbook(output);

						jxl.write.WritableFont wfont = new jxl.write.WritableFont(
								WritableFont.createFont("宋体"), 12);

						WritableCellFormat font = new WritableCellFormat(
								NumberFormats.TEXT);
						font.setFont(wfont);
						font.setAlignment(jxl.format.Alignment.CENTRE);
						font.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
						// 水平居中对齐

						// 竖直方向居中对齐

						jxl.write.WritableSheet ws = wwb.createSheet("Sheet1",
								1); // 设置标题.ws.addCell(new
						for (int l = 0; l < infos.length; l++) {
							ws.addCell(new Label(l, 0, infos[l], font));
							if (l == 0 || l == 1) {

								CellView cv = new CellView(); // 定义一个列显示样式
								cv.setFormat(font);// 把定义的单元格格式初始化进去
								cv.setSize(5 * 265);// 设置列宽度（不设置的话是0，不会显示）

								ws.setColumnView(l, cv);
							} else {
								CellView cv = new CellView(); // 定义一个列显示样式
								cv.setFormat(font);// 把定义的单元格格式初始化进去
								cv.setSize(50 * 265);// 设置列宽度（不设置的话是0，不会显示）
								ws.setColumnView(l, cv);
							}
						}
						for (int j = 0; j < list.size(); j++) {
							Map<String, Object> map = PropertyUtils
									.turnToEntity1(list.get(j));
							int i = 0;

							ws.addCell(new Label(i, j + 1,
									map.get("ruleID") != null ? map.get(
											"ruleID").toString() : null, font));

							ws.addCell(new Label(i + 1, j + 1, map
									.get("apartmentID") != null ? map.get(
									"apartmentID").toString() : null, font));
							ws.addCell(new Label(i + 2, j + 1, map
									.get("feeTypeName") != null ? map.get(
									"feeTypeName").toString() : null, font));
							ws.addCell(new Label(i + 3, j + 1, map
									.get("ruleName") != null ? map.get(
									"ruleName").toString() : null, font));
							ws.addCell(new Label(
									i + 4,
									j + 1,
									map.get("apartmentType") != null ? propFeeMeterType[Integer
											.parseInt(map.get("apartmentType")
													.toString())] : null, font));
							ws.addCell(new Label(i + 5, j + 1, map
									.get("buildingName") != null ? map.get(
									"buildingName").toString() : null, font));
							ws.addCell(new Label(i + 6, j + 1, map
									.get("unitName") != null ? map.get(
									"unitName").toString() : null, font));
							ws.addCell(new Label(i + 7, j + 1, map
									.get("apartmentNum") != null ? map.get(
									"apartmentNum").toString() : null, font));
							ws.addCell(new Label(i + 8, j + 1, nextTime
									.get("nextTime") != null ? nextTime.get(
									"nextTime").toString() : null, font));

						}
						wwb.write();
						if (wwb != null) {
							wwb.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {// 正常关闭输入输出流.
						if (fis != null) {
							fis.close();
						}
						if (output != null) {
							output.flush();
							output.close();
						}

					}

				} catch (Exception e) {
					e.printStackTrace();
					throw new WebApplicationException(e);

				}
			}
		};

		return Response.ok(stream, MediaType.APPLICATION_OCTET_STREAM).build();
	}

	@Override
	public Response getImportLogsInfo(HttpServletRequest servletRequest,
			String commID, String search, String tsCreate, String pageIndex,
			String pageSize) throws Exception {

		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/
		List<Map<String, Object>> list = propFeePollfeeImportLogService
				.findPropFeePollfeeImportLogByPage(commID, tsCreate,
						search == null ? null : search,
						pageUtils.getiPageIndex(), pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response getProllfeeByMap(HttpServletRequest servletRequest,
			HttpServletResponse servletResponse, Map<String, Object> params)
			throws Exception {
 String pageIndex=StringUtils.toString(params.get("pageIndex"), "1");
 String pageSize=StringUtils.toString(params.get("pageSize"), "10");

              if(params.get("pageIndex")==null){
	
	
            	  params.put("pageIndex","1");
                  }
              if(params.get("pageSize")==null){
            		
            		
            	  params.put("pageSize","10");
                  }
		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		
		/************************************************
		 * 查询列表
		 ************************************************/
		List<Map<String, Object>> list  =propFeePollfeeService.getProllfeeByMap(params);

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response editProllfee(HttpServletRequest servletRequest,
			HttpServletResponse servletResponse, PollfeeEditDto pollfeeEditDto)
			throws Exception {
		PageUtils pageUtils = this.validateLogin(servletRequest);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		pollfeeEditDto.setUerID(pageUtils.getBaseSession().getUserID());
		propFeePollfeeService.editProllfee(pollfeeEditDto);
		// TODO Auto-generated method stub
		return this.normalResp();
	}
}
